import { mapHelper } from '../../../utils/mapTools'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseImgUrl: getApp().globalData.IMG_URL,
    selectedGoods: Array,
    storeInfo: { id: "", deliveryHasSupport: 'N', deliveryMinCost: 0, deliveryMaxDistance: 0, locLat: 0, locLng: 0 },
    token: "",
    // 操作部分
    selectedTotalPrice: 0,
    selectedOldTotalPrice: 0,
    selectedTotalNum: 0,
    // 切换取货
    deliveryHasSelected: false,
    shippingAddress: {
      hasDefault: '', nickname: '', phone: '', address: "", id: '', latitude: 0,
      longitude: 0,
    },
    submitIsEnable: true,
    distanceValue: 0,
    // 时间选择器
    deliveryDateShow: false,
    deliveryDate: '今天',
    deliveryDateStart: "2024-05-16",
    deliveryDateEnd: "2050-12-31",
    deliveryTime: '立即取用',
    deliveryTimeStart: "00:00",
    deliveryTimeEnd: "23:59",

    // 是否加载收货地址
    isFiristLoad: true,
    // 更多信息
    orderRemark: '', // 订单备注
    bizNo: '',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // console.error("更新数据3: " + JSON.stringify(this.data))
    const token = wx.getStorageSync('token')
    this.setData({ token: token });
    // console.error("更新数据5: " + JSON.stringify(this.data))

    let that = this
    const eventChannel = this.getOpenerEventChannel()
    // eventChannel.emit('acceptDataFromOpenedPage', {data: 'test'});
    eventChannel.on('acceptDataFromOpenerPage', function (param) {
      that.setData({
        selectedGoods: param.selectedGoods,
        storeInfo: param.storeInfo,
        bizNo: param.bizNo,
        isFiristLoad: false
      })
      // console.error("门店信息: " + JSON.stringify(that.data.storeInfo))
      // 计算
      that.doCount()

      // 获取当前用户shouhuo地址
      that.getConsumerAddress4Default()
    })

    this.initDateTime()// 重置开始时间
  },
  onShow() {
    // 获取当前用户shouhuo地址
    if (!this.data.isFiristLoad) {
      this.getConsumerAddress4Default()
    }
  },
  // 计算
  doCount() {
    var totalPrice = 0
    var totalPriceOld = 0
    var selectedNum = 0

    // console.error("goodsPage = " + JSON.stringify(this.data.goodsPage))

    for (let index = 0; index < this.data.selectedGoods.length; index++) {
      let goods = this.data.selectedGoods[index]

      // console.error("goods.buyNum != undefined 前" + goods.buyNum)
      if (goods.buyNum != undefined && goods.buyNum != 0) {

        // 当前销售总价
        totalPrice = totalPrice + goods.buyNum * goods.goodsSalePrice

        // 原价计算  取最大值
        let flagPrice = goods.goodsFlagPrice > goods.goodsSalePrice ? goods.goodsFlagPrice : goods.goodsSalePrice
        // 原总价
        totalPriceOld = totalPriceOld + goods.buyNum * flagPrice
        // 选中数量
        selectedNum = selectedNum + goods.buyNum
      }
    }
    // console.error("更新数据1: " + JSON.stringify(this.data.selectedGoods))

    // 更新数据
    this.setData({
      selectedTotalPrice: new Number(totalPrice.toFixed(2)).valueOf(),
      selectedOldTotalPrice: new Number(totalPriceOld.toFixed(2)).valueOf(),
      selectedTotalNum: selectedNum
    })
    // console.error("更新数据2: " + JSON.stringify(this.data.selectedGoods))
  },
  doSubmitOrder() {
    const that = this;

    if (that.data.deliveryHasSelected && (this.data.shippingAddress.id == null || this.data.shippingAddress.id == '')) {
      wx.showToast({ title: '请选送货地址', icon: 'success', duration: 2000 })
      return
    }

    if (that.data.deliveryHasSelected && (this.data.distanceValue > this.data.storeInfo.deliveryMaxDistance)) {
      wx.showToast({ title: '超过配送范围', icon: 'success', duration: 2000 })
      return
    }

    const preUrl = getApp().globalData.SERVER_URL
    const url = preUrl + "fc/order/customer/add"
    // 入参
    let param = {
      bizType: "B2C",
      deliveryHopeDate: this.data.deliveryDate, // 今天/ 具体日期取货
      deliveryHopeTime: this.data.deliveryTime, // 取货时间：立即取用/ 具体时间取货
      shoppingCarStoreGoods: [
        {
          goodsList: this.data.selectedGoods, // 选中商品集合
          storeId: this.data.storeInfo.id, // 商品门店ID
          orderAllPrice: this.data.selectedOldTotalPrice, // 商品总价
          orderPayPrice: this.data.selectedTotalPrice, // 实付总价
          queueNum: this.data.bizNo
        }
      ],
      delivery: this.data.deliveryHasSelected, // 是否外卖配送
      shippingAddress: this.data.deliveryHasSelected ? this.data.shippingAddress : {}, // 收货地址
      payType: '0', // 0货到付款10微信支付20支付宝支付
      orderDesc: this.data.orderRemark,
    }

    wx.showLoading({ title: '提交中...' })
    wx.request({
      url: url,
      method: 'POST',
      data: param,
      header: {
        // 'content-type': 'application/x-www-form-urlencoded', // 默认值
        'X-Access-Token': that.data.token
      },
      success(res: any) {
        if (res.data.code == 200) {
          // console.error("结果: " + JSON.stringify(res.data))
          that.gotoOrderDetail(res.data.result.orderNo)
        } else {
          console.info(JSON.stringify(res))
        }
      },
      complete(_) {
        wx.hideLoading()
      }
    })
  },
  /**
   * 
   * @param orderNo 进入订单详情页
   */
  gotoOrderDetail(orderNo: String) {
    // console.error("redirectTo: " + orderNo)
    wx.redirectTo({
      url: '/pages/order/orderDetail/orderDetail?orderNo=' + orderNo
    })
  },
  goConsumerAddressList() {// 打开收货地址
    wx.navigateTo({ url: '/pages/apps/user/address/address4Shipping/address4Shipping' })
  },
  /**
   * 
   * @param 切换收货方式
   */
  radioChange(e: any) {
    // console.log('radio发生change事件，携带value值为：', e.detail.value)
    let deliveryHasSelected = e.detail.value == 'r1'
    this.setData({ deliveryHasSelected: deliveryHasSelected })
    // 计算是否可以配送
    var submitIsEnable = this.data.submitIsEnable
    let store = this.data.storeInfo

    if ('Y' == store.deliveryHasSupport // 门店支持配送
      && deliveryHasSelected // 又已经选择配送
    ) {
      // console.error('是否可提交：1')
      // console.error('是否可提交selectedTotalPrice：' + this.data.selectedTotalPrice)
      // console.error('是否可提交deliveryMinCost：' + store.deliveryMinCost)
      if (this.data.selectedTotalPrice < (store.deliveryMinCost * 100)) {// deliveryMinCost单位是元
        submitIsEnable = false
      } else {
        submitIsEnable = true
      }
    } else {
      submitIsEnable = true
    }
    this.setData({ submitIsEnable: submitIsEnable })
    // console.error('是否可提交：', this.data.submitIsEnable)
  },
  /**
  * 获得客户默认地址
  */
  getConsumerAddress4Default() {
    var shoppingAddressJSON = wx.getStorageSync('address_4_curr_shopping')
    if (shoppingAddressJSON != null && shoppingAddressJSON != '') {
      const shoppingAddress = JSON.parse(shoppingAddressJSON)
      this.setData({ shippingAddress: shoppingAddress })
      // 计算距离
      this.getDistance()
      console.error("url: 缓存数据")
    } else {
      var that = this
      const token = wx.getStorageSync('token')
      const preUrl = getApp().globalData.SERVER_URL
      const url = preUrl + "fc/emall/shippingAddress/defaultForCurrUser"
      // console.error("url: " + url)
      wx.request({
        url: url,
        method: 'GET',
        data: {
        },
        header: {
          // 'content-type': 'application/x-www-form-urlencoded', // 默认值
          'X-Access-Token': token,
          'Tenant-Id': '-1'
        },
        success(res: any) {
          // console.error("结果: " + JSON.stringify(res))
          wx.stopPullDownRefresh()
          if (res.data.code == 200) {
            if (res.data.result != null && res.data.result != '') {
              that.setData({ shippingAddress: res.data.result })
              // 计算距离
              that.getDistance()
              console.error("url: 网络数据")
            } else {
              console.error("暂无收货地址")
            }
          } else {
            console.info(JSON.stringify(res))
          }
        },
        complete(_) {
        }
      })
    }
  },
  // 选择时间-确定
  bindTimeChange: function (e: any) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({ deliveryTime: e.detail.value })
  },
  deliveryTimeClick() {
    // this.initDateTime()// 重置开始时间
  },
  // 选择时间-取消
  bindCancel(_: any) {
    this.setData({ deliveryDate: '今天', deliveryTime: '立即取用', })
  },
  // 选择日期-确定
  bindDateChange: function (e: any) {
    const dateStr = e.detail.value
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({ deliveryDate: dateStr })

    // 创建一个新的日期对象
    const now = new Date();
    // 获取日期的各个部分
    const year = now.getFullYear(); // 年份
    const month = now.getMonth() + 1; // 月份，0-11，所以需要+1
    const day = now.getDate(); // 日期号
    const dateString = year + "-" + (month < 10 ? '0' : '') + month + "-" + (day < 10 ? '0' : '') + day;

    const hours = now.getHours(); // 小时
    const minutes = now.getMinutes(); // 分钟
    // const seconds = now.getSeconds(); // 秒钟
    const timeString = (hours < 10 ? '0' : '') + hours + ":" + (minutes < 10 ? '0' : '') + minutes;
    // 判断是否是今天
    var deliveryTimeStart = "00:00"
    if (dateString == this.data.deliveryDate || '今天' == this.data.deliveryDate) {
      deliveryTimeStart = timeString
    }
    this.setData({ deliveryDateStart: dateString, deliveryTimeStart: deliveryTimeStart })
  },
  // 选择日期-确定
  bindDateCancel(_: any) {
    this.setData({ deliveryDate: '今天' })
    this.initDateTime()
  },
  initDateTime() {
    // 创建一个新的日期对象
    const now = new Date();
    // 获取日期的各个部分
    const year = now.getFullYear(); // 年份
    const month = now.getMonth() + 1; // 月份，0-11，所以需要+1
    const day = now.getDate(); // 日期号
    const hours = now.getHours(); // 小时
    const minutes = now.getMinutes(); // 分钟
    const seconds = now.getSeconds(); // 秒钟

    const dateString = year + "-" + (month < 10 ? '0' : '') + month + "-" + (day < 10 ? '0' : '') + day;
    var timeString = (hours < 10 ? '0' : '') + hours + ":" + (minutes < 10 ? '0' : '') + minutes;
    this.setData({ deliveryDateStart: dateString, deliveryTimeStart: timeString })
  },
  // 计算收货点到门店的距离
  getDistance() {
    const locLat4shippingAddress = this.data.shippingAddress.latitude
    const locLng4shippingAddress = this.data.shippingAddress.longitude
    const locLat4storeInfo = this.data.storeInfo.locLat
    const locLng4storeInfo = this.data.storeInfo.locLng

    // console.error("locLat4shippingAddress: " + locLat4shippingAddress)
    // console.error("locLng4shippingAddress: " + locLng4shippingAddress)
    // console.error("locLat4storeInfo: " + locLat4storeInfo)
    // console.error("locLng4storeInfo: " + locLng4storeInfo)

    var distance: number = mapHelper.getDistance(
      { lat: locLat4shippingAddress, lon: locLng4shippingAddress },
      { lat: locLat4storeInfo, lon: locLng4storeInfo })
    distance = Math.ceil(distance)
    this.setData({ distanceValue: distance })
    console.error("distance: " + distance)
  },
  bindOrderRemarkInput(e: any) {
    this.setData({ orderRemark: e.detail.value })
  },
})